<template>
  <el-form :model="form" label-width="auto" style="max-width: 600px">
    <el-form-item label="账号">
      <el-input v-model="form.userName" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.userPwd" show-password style="width: 1000px" />
    </el-form-item>
    <el-form-item label="验证码" prop="captcha">
      <el-input v-model="form.captcha" placeholder="请输入验证码"></el-input>
      <canvas ref="captchaCanvas" @click="refreshCaptcha"></canvas>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="login()">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import axios from "axios";
import { onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
import { useCounterStore } from "@/stores/counter";
import { KongaUrl } from "@/axios/axiosHelp";
const store = useCounterStore();
// do not use same name with ref
const form = reactive({
  userName: "",
  userPwd: "",
  captcha: "",
});
const captchaCanvas = ref(null);
const login = () => {
  //非空判断
  if (form.userName == "") {
    ElMessage.error("用户名不得为空");
    return;
  }
  if (form.userPwd == "") {
    ElMessage.error("密码不得为空");
    return;
  }
  // if (form.captcha == "") {
  //   ElMessage.error("验证码错误");
  //   return;
  // }
  console.log(form);
  KongaUrl("user/api/Backed/Login", {
    params: form,
  })
    .then((res) => {
      if (res.data.code == 100) {
        store.user.userName = res.data.data.userName;
        store.user.roleName = res.data.data.roleName;
        store.user.userId = res.data.data.userId;
        store.user.departmentId = res.data.data.departmentId;
        store.user.powerId = res.data.data.powerId;
        ElMessage.success(res.data.message);
        console.log(form);
        console.log(res.data.data);
        window.localStorage.setItem("token", res.data.token);
        // 数据提交后端要加入新的Token值
        axios.defaults.headers.common["Authorization"] =
          "Bearer " + res.data.token;
        router.push("/Main");
      } else {
        ElMessage.error(res.data.message);
      }
    });
};
// 当前生成的验证码
const captchaCode = ref("");

// 生成随机验证码
const generateCaptcha = () => {
  const characters =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let code = "";
  for (let i = 0; i < 4; i++) {
    code += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  captchaCode.value = code;
};

// 绘制验证码到 canvas 上
const drawCaptcha = () => {
  const canvas: any = captchaCanvas.value;
  const ctx = canvas.getContext("2d");
  canvas.width = 120;
  canvas.height = 40;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 设置背景颜色
  ctx.fillStyle = "#f0f0f0";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.strokeStyle = getRandomColor();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 绘制干扰点
  for (let i = 0; i < 50; i++) {
    ctx.beginPath();
    ctx.fillStyle = getRandomColor();
    const x = Math.random() * canvas.width;
    const y = Math.random() * canvas.height;
    ctx.arc(x, y, 1, 0, 2 * Math.PI);
    ctx.fill();
  }

  // 绘制验证码字符
  const fontSize = 24;
  ctx.font = `${fontSize}px Arial`;
  for (let i = 0; i < captchaCode.value.length; i++) {
    ctx.fillStyle = getRandomColor();
    ctx.fillText(
      captchaCode.value[i],
      20 + i * fontSize,
      20 + Math.random() * 10
    );
  }
};

// 生成随机颜色
const getRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  drawCaptcha();
  form.captcha = "";
};
onMounted(() => {
  generateCaptcha();
  drawCaptcha();
});
</script>
